//
//  FileDownload.m
//  CedarFinancePH
//
//  Created by lshenrong on 2018/8/6.
//  Copyright © 2018年 cedarhd. All rights reserved.
//

#import "FileDownload.h"
#import <AFNetworking/AFNetworking.h>
#import "CedarFileManager.h"

@interface FileDownload()//Library/Cache目录

@property (nonatomic,copy) NSString *folderPath;
@property (nonatomic,copy) NSString *folderName;

@property (nonatomic,copy) NSString *downloadUrl;

@property (nonatomic,strong) NSURLSessionDownloadTask *downloadTask;

@end


@implementation FileDownload

- (instancetype)initWithFolder:(NSString *)folderName{
    if(self =[super init]){
        self.folderName = folderName;
        self.isDownloading = NO;
        [self checkFolderIfNoExistCreate:folderName];
    }
    return self;
}

- (void)dealloc{
    CLog(@"FileDownload dealloc");
}

- (void)cancel{
    if(self.downloadTask){
        [self.downloadTask cancel];
    }
    self.isDownloading = NO;
}


//http://wind4app-bdys.oss-cn-hangzhou.aliyuncs.com/CMD_MarkDown.zip
- (void)startDownloadFile:(NSString *)fileUrl fileName:(NSString *)fileName{

  // fileUrl = @"http://wind4app-bdys.oss-cn-hangzhou.aliyuncs.com/CMD_MarkDown.zip";
    self.downloadUrl = fileUrl;
    
    /* 创建网络下载对象 */
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    /* 下载地址 */
    NSURL *url = [NSURL URLWithString:fileUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSString  *filePath = [self filePathWithFileUrl:fileUrl fileName:fileName];
    /* 开始请求下载 */
    self.downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        if (self.downloadBlock) {
            self.downloadBlock(downloadProgress.fractionCompleted , DownloadStatusStart, self.downloadUrl);
        }
        CLog(@"下载进度：%.0f％", downloadProgress.fractionCompleted * 100);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        /* 设定下载到的位置 */
        return [NSURL fileURLWithPath:filePath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        CLog(@"下载完成 %@",[NSThread currentThread]);
        self.isDownloading = NO;
        if (self.downloadBlock) {
            self.downloadBlock(100,error?DownloadStatusError:DownloadStatusComplete, self.downloadUrl);
        }
    }];
    self.isDownloading = YES;
    [self.downloadTask resume];
}


- (NSString *)filePathWithFileUrl:(NSString *)fileUrl  fileName:(NSString *)fileName{
    NSString *saveFileName = fileName;
    if(IsEmptyStr(fileName)){
         saveFileName = [fileUrl lastPathComponent];
    }
    NSString *filePath = [self.folderPath stringByAppendingPathComponent:saveFileName];
    return filePath;
}


- (BOOL)checkFolderIfNoExistCreate:(NSString *)floderName{
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    self.folderPath  = [cachePath stringByAppendingPathComponent:floderName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:self.folderPath isDirectory:&isDir];
    if(!(existed && isDir)) {
        BOOL result = [fileManager createDirectoryAtPath:self.folderPath withIntermediateDirectories:YES attributes:nil error:nil];
        CLog(@"folder :%@ create: %d",floderName,result);
        if(!result){
            return NO;
        }
    }
    return YES;
}







@end
